package com.rui.study.algorithm.L_深入理解JVM_并发;

/**
 * @program: study
 * @description:
 * @author: Yaowr
 * @create: 2019-03-04 16:12
 **/
public class Test {

    private static final int THREADS_NUM = 100;
    public static final int LOOP_NUM = 100;
    public static final double STATISTIC_NUM = 100;

    /**
     * volatile变量在进行“++”操作也是不安全的
     * 使用java.util.concurrent包的原子类可以实现“++”操作的原子性
     */
    private static volatile int sum = 0;
//    private static AtomicInteger sum = new AtomicInteger(0);

    public static void inc() {
        sum++;
//        sum.getAndIncrement();
    }

    public static boolean run() {
        Thread[] threads = new Thread[THREADS_NUM];
        for (int i = 0; i < THREADS_NUM; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < LOOP_NUM; j++) {
                    inc();
                }
//                System.out.println(Thread.currentThread().getName() + " is over!");
            }, "My-Algorithm-" + i);
            threads[i].start();
        }

        for (int i = 0; i < THREADS_NUM; i++) {

            try {
                threads[i].join();
//                System.out.println(threads[i].getName() + " is Die!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
//        System.out.println(Thread.activeCount());

        System.out.println(sum);
        return sum == THREADS_NUM * LOOP_NUM;
//        return sum.get() == THREADS_NUM * LOOP_NUM;
    }

    public static void statistic() {
        int count = 0;
        for (int i = 0; i < STATISTIC_NUM; i++) {
            count += (run() ? 0 : 1);
            sum = 0;
//            sum.set(0);
        }
        System.out.println("Failed Ratio: [" + count/STATISTIC_NUM*100 + "%]");
    }

    public static void main(String[] args) {
        statistic();
    }
}
